package com.yami.shop.webservice.common.service.impl;

import cn.hutool.extra.mail.MailException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.yami.shop.bean.enums.PaySeviceTypeCode;
import com.yami.shop.common.bean.HSExchange;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.util.DateUtils;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.webservice.common.service.WapiFundService;
import com.yami.shop.webservice.common.util.MD5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 * @author zhangchaoqun
 * @date 2021-10-13
 */
@Service
public class WapiFundServiceImpl implements WapiFundService
{
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ShopConfig shopConfig;
    @Override
    public JSONObject getWapiFund(String userId) {
        if(StringUtils.isEmpty(userId)){
            throw new MailException("userId为空");
        }
        HSExchange hsExchange = shopConfig.getAPIExchange();
        //获取请求内容
        JSONObject biz_content = new JSONObject();
        biz_content.put("exchangeId","0");
        biz_content.put("fundAccount",null);
        biz_content.put("userId",userId);
        //基础参数
        Map<String, Object> orgParam = new HashMap<>();
        orgParam.put("version", "v1");
        orgParam.put("app_id",hsExchange.getAppId());
        orgParam.put("charset","UTF-8");
        orgParam.put("timestamp", DateUtils.dateToString(new Date()));
        orgParam.put("biz_content",biz_content);
        //获取sign
        orgParam.put("sign", MD5Utils.md5Two("UTF-8",biz_content.toString(),hsExchange.getAppSecret()));
        StringBuilder targetUrl = new StringBuilder();
        for (Map.Entry<String, Object> entry : orgParam.entrySet()) {
            targetUrl.append(entry.getKey()).append("=").append( entry.getValue()).append("&");
        }
        String param = targetUrl.substring(0, (targetUrl.length() - 1)).toString();
        // 组装外层通用参数 发起审核通知
        log.info(userId+"用户获取恒生交易所金额地址"+hsExchange.getAppUrl()+"/openapi/"+ PaySeviceTypeCode.function_id11);
        log.info(userId+"用户获取恒生交易所金额参数"+param);
        String result =  null;;
        try{
            result = HttpRequest.post(hsExchange.getAppUrl()+"/openapi/"+PaySeviceTypeCode.function_id11).body(param).setConnectionTimeout(60000).execute().body();
        }catch (Exception e){
            log.info(userId+"用户获取恒生交易所金额超市重试"+param);
            result = HttpRequest.post(hsExchange.getAppUrl()+"/openapi/"+PaySeviceTypeCode.function_id11).body(param).setConnectionTimeout(60000).execute().body();
        }
        log.info(userId+"用户获取恒生交易所金额返回结果"+result);
        JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                JSONObject res = jsonObject.getJSONObject("data");
                if(!"".equals(res.getString("errorNo")) && !"0000".equals(res.getString("errorNo"))){
                    throw  new MailException(res.getString("errorInfo"));
                }
                JSONArray list= res.getJSONArray("items");
                if(list==null||list.size()==0){
                    throw new MailException("交易市场未开通");
                }
                //可用=余额-冻结 frozenBalance   currenBalance  canUseBalance
                for (int i = 0 ;i< list.size();i++) {
                    JSONObject ob = (JSONObject)list.get(i);
                    if(PaySeviceTypeCode.marketHNDX.equals(ob.getString("marketId"))){
                        return  ob;
                    }
                }
                throw new MailException("交易账户不存在");
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public JSONObject fundPay(String biz_content) throws MailException {
        //获取请求内容
        //基础参数
        HSExchange hsExchange = shopConfig.getAPIExchange();
        JSONObject jbject = JSONObject.parseObject(biz_content);
        jbject.put("transDate",DateUtils.dateToStrYmdTwo(new Date()));
        jbject.put("needTransaction","Y");
        jbject.put("isTradeGate","Y");
        jbject.put("marketId",PaySeviceTypeCode.marketHNDX);
//        jbject.put("outBizNo",outBizNo);
//        jbject.put("busiName",busiName);
//        jbject.put("marketId",PaySeviceTypeCode.marketId);
        //List<FundVo>-SettAtomicRequest
        jbject.put("settAtomicRequests",jbject.getJSONArray("list"));
        jbject.put("list",null);
        Map<String, Object> orgParam = new HashMap<>();
        orgParam.put("version", "v1");
        orgParam.put("app_id",hsExchange.getAppId());
        orgParam.put("charset","UTF-8");
        orgParam.put("timestamp", DateUtils.dateToString(new Date()));
        orgParam.put("biz_content",jbject.toJSONString());
        //获取sign
        orgParam.put("sign", MD5Utils.md5Two("UTF-8",jbject.toJSONString(),hsExchange.getAppSecret()));
        StringBuilder targetUrl = new StringBuilder();
        for (Map.Entry<String, Object> entry : orgParam.entrySet()) {
            targetUrl.append(entry.getKey()).append("=").append( entry.getValue()).append("&");
        }
        String param = targetUrl.substring(0, (targetUrl.length() - 1)).toString();
        // 组装外层通用参数 发起审核通知
        log.info("支付恒生交易所地址"+hsExchange.getAppUrl()+"/openapi/"+PaySeviceTypeCode.function_id8);
        log.info("支付恒生交易所参数"+param);
        String result = null;
        try{
             result = HttpRequest.post(hsExchange.getAppUrl()+"/openapi/"+PaySeviceTypeCode.function_id8).body(param).setConnectionTimeout(60000).execute().body();
        }catch (Exception e){
            log.info("支付恒生交易超市重试"+param);
             result = HttpRequest.post(hsExchange.getAppUrl()+"/openapi/"+PaySeviceTypeCode.function_id8).body(param).setConnectionTimeout(60000).execute().body();
        }
        log.info("支付恒生交易所返回结果"+result);
        JSONObject jsonObject =  null;
        try {
            jsonObject =  JSON.parseObject(result);
        }catch (Exception e){
            log.error("apigataway超时"+result);
            throw new MailException("超时"+result);
        }
        // 组装外层通用参数 发起审核通知
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                JSONObject res = jsonObject.getJSONObject("data");
                if(!"".equals(res.getString("errorNo")) && !"0000".equals(res.getString("errorNo")) && !"0".equals(res.getString("errorNo"))){
                    throw  new MailException(res.getString("errorInfo"));
                }
                return res;
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

	@Override
	public JSONObject getWapiFundOutRecord( String biz_content)
			throws MailException {
        //基础参数
        HSExchange hsExchange = shopConfig.getAPIExchange();
        JSONObject jbject = JSONObject.parseObject(biz_content);
        jbject.put("tradeMode",PaySeviceTypeCode.tradeMode);
        Map<String, Object> orgParam = new HashMap<>();
        orgParam.put("version", "v1");
        orgParam.put("app_id",hsExchange.getAppId());
        orgParam.put("charset","UTF-8");
        orgParam.put("timestamp", DateUtils.dateToString(new Date()));
        orgParam.put("biz_content",jbject.toJSONString());
        //获取sign
        orgParam.put("sign", MD5Utils.md5Two("UTF-8",jbject.toJSONString(),hsExchange.getAppSecret()));
        StringBuilder targetUrl = new StringBuilder();
        for (Map.Entry<String, Object> entry : orgParam.entrySet()) {
            targetUrl.append(entry.getKey()).append("=").append( entry.getValue()).append("&");
        }
        String param = targetUrl.substring(0, (targetUrl.length() - 1)).toString();
        // 组装外层通用参数 发起审核通知
        log.info("支付流水恒生交易所地址"+hsExchange.getAppUrl()+"/openapi/"+PaySeviceTypeCode.function_id13);
        log.info("支付流水恒生交易所参数"+param);
        String result = null;
        try{
             result = HttpRequest.post(hsExchange.getAppUrl()+"/openapi/"+PaySeviceTypeCode.function_id13).body(param).setConnectionTimeout(60000).execute().body();
        }catch (Exception e){
            log.info("支付流水恒生交易超时重试"+param);
             result = HttpRequest.post(hsExchange.getAppUrl()+"/openapi/"+ PaySeviceTypeCode.function_id13).body(param).setConnectionTimeout(60000).execute().body();
        }
        log.info("支付流水恒生交易所返回结果"+result);
        JSONObject jsonObject =  null;
        try {
            jsonObject =  JSON.parseObject(result);
        }catch (Exception e){
            log.error("apigataway超时"+result);
            throw new MailException("超时"+result);
        }
        // 组装外层通用参数 发起审核通知
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                JSONObject ress = jsonObject.getJSONObject("data");
                return ress;
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
	}


}
